package com.crm.system.service.impl.returnMoney;

import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.dao.mapper.customMapper.returnMoneyManagerCustomMapper.BankOrderCustomMapper;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerPay;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.returnMoney.*;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.returnMoney.BankFlowExamineQO;
import com.crm.model.vo.customerContractManager.CustomerContractDetailVO;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.returnMoney.BankFlowExamineVO;
import com.crm.model.vo.returnMoney.BankOrderRelateVO;
import com.crm.model.vo.returnMoney.FinanceProductOderInfoVO;
import com.crm.model.vo.returnMoney.ReturnMoneyVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPayDbService;
import com.crm.service.finishOrderProductManager.FinishOrderProductDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.*;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.finishOrderProductManager.FinishOrderProductService;
import com.crm.system.service.orderManager.CustomerProductOrderService;
import com.crm.system.service.returnMoney.BankFlowExamineService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
@Slf4j
public class BankFlowExamineServiceImpl implements BankFlowExamineService {

    @Autowired
    private BankFlowExamineDbService bankFlowExamineDbService;
    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;
    @Autowired
    private BankFlowDbService bankFlowDbService;
    @Autowired
    private ReturnMoneyLogDbService returnMoneyLogDbService;
    @Autowired
    private FinishOrderProductDbService finishOrderProductDbService;
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private ReturnMoneyService returnMoneyService;
    @Autowired
    private FinishOrderProductService finishOrderProductService;
    @Autowired
    private BankOrderCustomMapper bankOrderCustomMapper;
    @Autowired
    private CustomerPayDbService customerPayDbService;
    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerProductOrderService customerProductOrderService;
    @Autowired
    private CustomerContractService customerContractService;

    @Override
    public DhPageInfo<BankFlowExamineVO> selectPageList(Integer pageIndex, Integer pageSize, BankFlowExamineQO bankFlowExamineQO) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        if(!"3".equals(userAccount.getDeptId())){
            bankFlowExamineQO.setCompanyId(userAccount.getCompanyId());
        }

        Integer dateUnit = 0;
        if (StringUtils.isNotBlank(bankFlowExamineQO.getDateType())) {
            if ("thisWeek".equals(bankFlowExamineQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(bankFlowExamineQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("day".equals(bankFlowExamineQO.getDateType())) {
                //今天
                dateUnit = 3;
            }
        }

        bankFlowExamineQO.setDateUnit(dateUnit);
        List<BankFlowExamineVO> list = bankFlowExamineDbService.selectList(bankFlowExamineQO);
        PageInfo<BankFlowExamineVO> pageInfo=new PageInfo<>(list);
        return new DhPageInfo<BankFlowExamineVO>(pageInfo,list);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse examine(BankFlowExamine bankFlowExamine) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //3是总部财务
        if (!"3".equals(userAccount.getDeptId())){
            return new DhResponse(ResponseCodeEnum.NO_AUTH.getResponseCode());
        }
        if(StringUtils.isBlank(bankFlowExamine.getExamineId()) || bankFlowExamine.getExamineState() == null){
            return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }
        if(bankFlowExamine.getExamineState() != 1 && bankFlowExamine.getExamineState() != 2){
            return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }
        if(bankFlowExamine.getExamineInfo() != null && bankFlowExamine.getExamineInfo().length() > 300){
            bankFlowExamine.setExamineInfo(bankFlowExamine.getExamineInfo().substring(0,300));
        }
        BankFlowExamine oldExamine = bankFlowExamineDbService.selectByExamineId(bankFlowExamine.getExamineId());
        if(oldExamine == null || (oldExamine.getDeleteStatus() != null && oldExamine.getDeleteStatus() == 1)){
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_NOT_EXIST.getResponseCode());
        }
        if(oldExamine.getExamineState() == 1){
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_FAIL_1.getResponseCode());
        }
        if(oldExamine.getExamineState() == 2){
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_FAIL_2.getResponseCode());
        }
        //审核类型，0-单笔流水解除关联，1-订单整单解除关联
        if(oldExamine.getExamineType() != null){
            if(oldExamine.getExamineType() == 0){
                if(StringUtils.isNoneBlank(oldExamine.getCustomerPayId())){
                    //充值码解除关联审核
                    return examineByPay(bankFlowExamine, oldExamine);
                }else{
                    //单笔流水解除关联审核
                    return examineByFlow(bankFlowExamine, oldExamine);
                }
            }else if(oldExamine.getExamineType() == 1){
                //订单整单解除关联审核
                return examineByOrder(bankFlowExamine, oldExamine);
            }else if(oldExamine.getExamineType() == 2){
//                //预回款审核
//                return examineForPrepareReturn(bankFlowExamine, oldExamine);
            }
        }
//        log.error("错误的审核类型！！！");
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse examineByOrder(BankFlowExamine bankFlowExamine, BankFlowExamine oldExamine) {
        //订单id
        String productOrderId = oldExamine.getProductOrderId();

        //产品订单
        CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);

        //订单回款记录
        List<ReturnMoneyVO> returnMoneyVOList = returnMoneyDbservice.selectListByOrderId(productOrderId);

        if(bankFlowExamine.getExamineState() == 1){
            if(oldCustomerProductOrder != null && "5".equals(oldCustomerProductOrder.getOrderStatus())){//预回款订单不能通过审核
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_BY_ORDER_PASS_FAIL_PRE_RETURN.getResponseCode());
            }
            if(returnMoneyVOList.size() == 0){//不能通过审核：没有回款记录
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_BY_ORDER_PASS_FAIL_NOT_RETURN_MONEY.getResponseCode());
            }

            for(ReturnMoneyVO vo : returnMoneyVOList){
                if(vo.getBankOrderId() == null){//不能通过审核：有未关联流水的回款记录
                    return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_BY_ORDER_PASS_FAIL_NOT_ALL_HAS_SERIAL.getResponseCode());
                }
                if(vo.getReturnStatus() != null && vo.getReturnStatus() == 0){//不能通过审核：有预回款记录
                    return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_BY_ORDER_PASS_FAIL_HAS_PRE_RETURN.getResponseCode());
                }
                if(vo.getCloseStatus() != null && vo.getCloseStatus() == 1){//不能通过审核：有封账的回款记录
                    return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_BY_ORDER_PASS_FAIL_HAS_CLOSE.getResponseCode());
                }
            }
        }

        //查询流水关联列表
        List<BankOrderRelateVO> relatedList = bankOrderCustomMapper.queryBankRelatedByProductOrderId(productOrderId);

        //流水、回款记录关联关系
        Map<String, String> flowReturnMoneyMap = new HashMap<>();

        for(BankOrderRelateVO bankOrderRelateVO : relatedList) {
            flowReturnMoneyMap.put(bankOrderRelateVO.getReturnMoneyId(), bankOrderRelateVO.getFlowId());
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Date now = new Date();
        //流水审核通过后
        //删除回款记录，插入回款操作记录
        //修改订单完成的产品表的回款时间为空、产品状态为未回款
        //修改产品订单表的订单状态为未回款即1，订单状态从2<已完成>到其他状态则卡作废，修改已回款金额合计为0
        //修改合同表到款时间为空、合同总回款金额为0、合同回款状态为0，合同状态为1（订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>）
        //修改银行流水的可用金额、已用金额、关联状态
        if(bankFlowExamine.getExamineState() == 1){
            FinishOrderProduct fop = new FinishOrderProduct();
            fop.setProductOrderId(productOrderId);
            //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
            fop.setProductStatus("0");
            //业绩金额
            fop.setGradeMoney(new BigDecimal("0"));
            fop.setArriveTime(null);
            fop.setUpdatePeopleId(userAccount.getAccountId());
            fop.setUpdateTm(now);
            finishOrderProductDbService.updateArriveTimeAndOtherSelectiveInfoByProductOrderId(fop);
//            log.info("流水审核通过（订单），修改订单完成的产品表的回款时间为空、产品状态为未回款、业绩金额为0");

            //兑换码发送状态 0否;1是
            Integer exchangeCodeSendingStatus = null;

            //订单状态从2<已完成>到其他状态则卡作废，卡作废时，将订单表的兑换码发送状态改为否
            if(oldCustomerProductOrder != null && "2".equals(oldCustomerProductOrder.getOrderStatus())){
                exchangeCodeSendingStatus = 0;
                int count = 0;
                //查询该订单产品
                List<FinishOrderProductVO> fopList = finishOrderProductDbService.selectListByProductOrderId(productOrderId, null);
                for(FinishOrderProductVO finishOrderProductVO : fopList){
                    String fopNum = finishOrderProductVO.getFinishOrderProductNum();
                    if(StringUtils.isNoneBlank(fopNum)){
                        customerProductOrderService.backProduct(productOrderId, fopNum);
                        count++;
                    }
                }
//            if(count == 0){
//                log.info("流水审核通过（订单），无卡作废");
//            }else{
//                log.info("流水审核通过（订单），有" + count + "张卡作废");
//            }
            }

            CustomerProductOrder cpo = new CustomerProductOrder();
            cpo.setProductOrderId(productOrderId);
            cpo.setOrderStatus("1");
            cpo.setUpdatePeopleId(userAccount.getAccountId());
            cpo.setUpdateTm(now);
            cpo.setPaidBackAmount(new BigDecimal("0"));
            cpo.setOldOrder("-100");
            cpo.setExamineState((short) 0);
            cpo.setExchangeCodeSendingStatus(exchangeCodeSendingStatus);
//            log.info("流水审核通过（订单），修改产品订单表的订单状态为未回款即1、已回款金额合计为0");
            customerProductOrderDbService.updateOrderSelective(cpo);

            if(oldCustomerProductOrder == null){
//                log.error("流水审核时找不到订单");
            }else{
                CustomerContract customerContract = new CustomerContract();
                customerContract.setContractId(oldCustomerProductOrder.getContractId());
                //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
                //订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>
                customerContract.setContractStatus("1");
                //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
                customerContract.setPaymentStatus("0");
                customerContract.setPaymentDate(null);
                customerContract.setContractTotalPaymentAmount(new BigDecimal("0"));
                customerContract.setUpdatePeopleId(userAccount.getAccountId());
                customerContract.setUpdateTm(now);
                customerContractDbService.updateArriveTimeAndOtherSelectiveInfo(customerContract);
//                log.info("流水审核通过（订单），修改合同表到款时间为空、合同总回款金额为0、合同回款状态为0，合同状态为1");
            }

            //修改银行流水的可用金额、已用金额、关联状态------------------------------------------------start
//            //查询流水关联列表
//            List<BankOrderRelateVO> relatedList = bankOrderCustomMapper.queryBankRelatedByProductOrderId(productOrderId);

            //需要更改的流水信息
            Map<String, BankFlow> changeAmountMap = new HashMap<>();
            //原流水信息
            Map<String, BankFlow> oldAmountMap = new HashMap<>();
//            //流水、回款记录关联关系
//            Map<String, String> flowReturnMoneyMap = new HashMap<>();

            for(BankOrderRelateVO bankOrderRelateVO : relatedList){
//                flowReturnMoneyMap.put(bankOrderRelateVO.getReturnMoneyId(), bankOrderRelateVO.getFlowId());
                BankFlow bfAmount = changeAmountMap.get(bankOrderRelateVO.getFlowId());
                if(bfAmount == null){
                    bfAmount = new BankFlow();
                    bfAmount.setAvailableAmount(new BigDecimal("0"));
                    bfAmount.setUsedAmount(new BigDecimal("0"));
                }

                BankFlow oldAmount = oldAmountMap.get(bankOrderRelateVO.getFlowId());
                if(oldAmount == null){
                    oldAmount = new BankFlow();
                    oldAmount.setFlowId(bankOrderRelateVO.getFlowId());
                    oldAmount.setCreditMoney(bankOrderRelateVO.getCreditMoney()==null?new BigDecimal("0"):bankOrderRelateVO.getCreditMoney());
                    oldAmount.setAvailableAmount(bankOrderRelateVO.getAvailableAmount()==null?new BigDecimal("0"):bankOrderRelateVO.getAvailableAmount());
                    oldAmount.setUsedAmount(bankOrderRelateVO.getUsedAmount()==null?new BigDecimal("0"):bankOrderRelateVO.getUsedAmount());
                    oldAmountMap.put(bankOrderRelateVO.getFlowId(), oldAmount);
                }

                BigDecimal arriveMoney = bankOrderRelateVO.getArriveMoney()==null?new BigDecimal("0"):bankOrderRelateVO.getArriveMoney();

                //可用金额
                bfAmount.setAvailableAmount(bfAmount.getAvailableAmount().add(arriveMoney));
                //已用金额
                bfAmount.setUsedAmount(bfAmount.getUsedAmount().add(arriveMoney));

                changeAmountMap.put(bankOrderRelateVO.getFlowId(), bfAmount);
            }
            Iterator<Map.Entry<String, BankFlow>> it = oldAmountMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, BankFlow> entry = it.next();
                String flowId = entry.getKey();
                BankFlow bf = entry.getValue();
                bf.setUpdateTime(now);

                BigDecimal availableAmount = new BigDecimal("0");
                BigDecimal usedAmount = new BigDecimal("0");

                BankFlow changeAmount = changeAmountMap.get(flowId);
                if(changeAmount != null){
                    if(changeAmount.getAvailableAmount() != null){
                        availableAmount = changeAmount.getAvailableAmount();
                    }
                    if(changeAmount.getUsedAmount() != null){
                        usedAmount = changeAmount.getUsedAmount();
                    }
                }
                //可用金额加充值金额
                bf.setAvailableAmount(bf.getAvailableAmount().add(availableAmount));
                //已用金额减充值金额
                bf.setUsedAmount(bf.getUsedAmount().subtract(usedAmount));
                //若贷方金额等于可用金额，关联状态改为N未关联，否则改为B部分关联
                if(bf.getCreditMoney().compareTo(bf.getAvailableAmount()) == 0){
                    bf.setRelationState("N");
                }else{
                    bf.setRelationState("B");
                }
                //修改可用金额、已用金额、关联状态
                bankFlowDbService.updateByPrimaryKeySelective(bf);
//                log.info("流水审核通过（订单），修改银行流水记录(" + bf.getFlowId() + ")的可用金额、已用金额、关联状态");
            }
            //修改银行流水的可用金额、已用金额、关联状态------------------------------------------------end

            //删除流水订单关联关系
            bankOrderCustomMapper.delByProductOrderId(productOrderId);
//            log.info("流水审核通过（订单），删除流水订单关联关系");

            //删除未审核的记录
            bankFlowExamineDbService.delByProductOrderId(productOrderId);
//            log.info("流水审核通过（订单），删除未审核的单笔流水记录");

            returnMoneyDbservice.delReturnMoneyByOrderId(productOrderId, userAccount.getAccountId());
//            log.info("流水审核通过（订单），删除订单全部回款记录");
        }else{//流水审核拒绝，修改订单表的审核状态为正常
            CustomerProductOrder cpo = new CustomerProductOrder();
            cpo.setProductOrderId(productOrderId);
            cpo.setExamineState((short) 0);
            cpo.setUpdatePeopleId(userAccount.getAccountId());
            cpo.setUpdateTm(now);
            customerProductOrderDbService.updateOrderSelective(cpo);
//            log.info("流水审核拒绝（订单），修改订单表的审核状态为正常");
        }

        for(ReturnMoneyVO vo : returnMoneyVOList){
            ReturnMoneyLog log = new ReturnMoneyLog();
            log.setReturnMoneyLogId(CommonUtils.getGUID());
            log.setFlowId(flowReturnMoneyMap.get(vo.getReturnMoneyId()));
            log.setReturnMoneyId(vo.getReturnMoneyId());
            if(bankFlowExamine.getExamineState() == 1){//审核通过
                log.setNewData("备注：流水审核通过（订单），删除回款记录，金额：" + vo.getArriveMoney());
                log.setOperatorType(2);  //操作类型 1修改 2删除 3退款 4关联 5调减
            }else{//审核拒绝
                log.setNewData("备注：流水审核拒绝（订单）");
                log.setOperatorType(1);  //操作类型 1修改 2删除 3退款 4关联 5调减
            }
            log.setCreatePeopleId(userAccount.getAccountId());
            log.setCreateTm(now);
            //插入回款操作记录
            returnMoneyLogDbService.addReturnMoneyLog(log);
        }

//        if(returnMoneyVOList.size() == 0){
//            log.info("流水审核" + ( bankFlowExamine.getExamineState()==1 ? "通过" : "拒绝" ) + "（订单），没有回款记录");
//        }

        bankFlowExamine.setExaminePeopleId(userAccount.getAccountId());
        bankFlowExamine.setExamineTime(now);
        bankFlowExamineDbService.updateByPrimaryKeySelective(bankFlowExamine);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse examineByFlow(BankFlowExamine bankFlowExamine, BankFlowExamine oldExamine) {
        //银行流水记录id
        String flowId = oldExamine.getRelationId();
        //原银行流水记录
        BankFlow oldBankFlow = bankFlowDbService.selectByFlowId(flowId);
//        if(oldBankFlow == null){
//            log.error("流水审核时找不到流水记录");
//        }
        //回款id
        String returnMoneyId = oldExamine.getReturnMoneyId();
//        if(StringUtils.isBlank(returnMoneyId)){
//            log.error("流水审核时找不到回款id");
//        }
        //原回款记录
        ReturnMoneyVO oldReturnMoney = returnMoneyDbservice.getReturnMoenyInfoById(returnMoneyId);
//        if(oldReturnMoney == null){
//            log.error("流水审核时找不到回款记录");
//        }

        //订单id
        String productOrderId = oldExamine.getProductOrderId();
//        if(StringUtils.isBlank(productOrderId)){
//            log.error("流水审核时找不到订单id");
//        }

        //到款金额
        BigDecimal arriveMoney = (oldReturnMoney==null || oldReturnMoney.getArriveMoney()==null) ? new BigDecimal("0") : oldReturnMoney.getArriveMoney();

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Date now = new Date();

        //流水审核通过后
        //删除回款记录，插入回款操作记录
        //修改银行流水的可用金额、已用金额、关联状态
        //修改订单完成的产品表的业绩金额、回款时间、产品状态（未回款或部分回款或已回款<金额为0的情况>）
        //修改产品订单表的订单状态（未回款或部分回款或已回款<金额为0的情况>），订单状态从2<已完成>到其他状态则卡作废，修改已回款金额合计
        //修改合同表到款时间、合同总回款金额、合同状态（订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>）
        if(bankFlowExamine.getExamineState() == 1){
            if(oldReturnMoney != null && oldReturnMoney.getCloseStatus() != null && oldReturnMoney.getCloseStatus() == 1){//不能通过审核：回款记录已封账
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_PASS_FAIL_HAS_CLOSE.getResponseCode());
            }
            if(StringUtils.isNoneBlank(returnMoneyId)){
                if(oldReturnMoney != null && oldBankFlow != null){
                    //贷方金额
                    BigDecimal creditMoney = oldBankFlow.getCreditMoney()==null?new BigDecimal("0"):oldBankFlow.getCreditMoney();
                    //可用金额
                    BigDecimal availableAmount = oldBankFlow.getAvailableAmount()==null?new BigDecimal("0"):oldBankFlow.getAvailableAmount();
                    //已用金额
                    BigDecimal usedAmount = oldBankFlow.getUsedAmount()==null?new BigDecimal("0"):oldBankFlow.getUsedAmount();
                    //可用金额加到款金额
                    availableAmount = availableAmount.add(arriveMoney);
                    //已用金额减到款金额
                    usedAmount = usedAmount.subtract(arriveMoney);

                    BankFlow bf = new BankFlow();
                    bf.setFlowId(flowId);
                    bf.setUpdateTime(now);
                    bf.setAvailableAmount(availableAmount);
                    bf.setUsedAmount(usedAmount);
                    //若贷方金额等于可用金额，关联状态改为N未关联，否则改为B部分关联
                    if(creditMoney.compareTo(availableAmount) == 0){
                        bf.setRelationState("N");
                    }else{
                        bf.setRelationState("B");
                    }
                    //修改可用金额、已用金额、关联状态
                    bankFlowDbService.updateByPrimaryKeySelective(bf);
//                    log.info("流水审核通过，修改银行流水记录的可用金额、已用金额、关联状态");
                }

                ReturnMoney rm = new ReturnMoney();
                rm.setReturnMoneyId(returnMoneyId);
                rm.setUpdateBy(userAccount.getAccountId());
                rm.setDelFlag(1);
                rm.setUpdateTm(now);
                //删除回款
                returnMoneyDbservice.updateReturnMoney(rm);
//                log.info("流水审核通过，删除回款");
            }

            //产品号
            String finishOrderProductNum = oldExamine.getFinishOrderProductNum();
            FinishOrderProductVO oldFinishOrderProduct = finishOrderProductDbService.selectFinishOrderProductByNumber(finishOrderProductNum);
            //产品订单
            CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);
            //合同id
            String contractId = oldCustomerProductOrder!=null ? oldCustomerProductOrder.getContractId() : null;
            //合同
            CustomerContract oldCustomerContract = customerContractDbService.selectContractById(contractId);

            //各表状态
            Map<String, String> status = this.getStatus(productOrderId, finishOrderProductNum, oldFinishOrderProduct, oldCustomerContract);

            //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
            String productStatus = status.get("productStatus");
            //订单状态，1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）;5:预回款
            String orderStatus = status.get("orderStatus");
            //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
            String paymentStatus = status.get("paymentStatus");
            //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
            String contractStatus = status.get("contractStatus");
            //兑换码发送状态 0否;1是
            Integer exchangeCodeSendingStatus = null;

            //订单状态从2<已完成>到其他状态则卡作废，卡作废时，将订单表的兑换码发送状态改为否
            if(oldCustomerProductOrder != null && "2".equals(oldCustomerProductOrder.getOrderStatus()) && !"2".equals(orderStatus)){
                exchangeCodeSendingStatus = 0;
                int count = 0;
                //查询该订单产品
                List<FinishOrderProductVO> fopList = finishOrderProductDbService.selectListByProductOrderId(productOrderId, null);
                for(FinishOrderProductVO finishOrderProductVO : fopList){
                    String fopNum = finishOrderProductVO.getFinishOrderProductNum();
                    if(StringUtils.isNoneBlank(fopNum)){
                        customerProductOrderService.backProduct(productOrderId, fopNum);
                        count++;
                    }
                }
//            if(count == 0){
//                log.info("流水审核通过，无卡作废");
//            }else{
//                log.info("流水审核通过，有" + count + "张卡作废");
//            }
            }

            if(StringUtils.isBlank(finishOrderProductNum)){
//                log.error("流水审核时找不到产品号");
            }else{

                //产品最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByFinishOrderProductNum(finishOrderProductNum);
                //产品最近到款时间
                Date arriveTime = null;
                if(lastReturnMoney != null){
                    arriveTime = lastReturnMoney.getArriveTime();
                }

                //订单完成的产品
                FinishOrderProduct fop = new FinishOrderProduct();

                //业绩换算比例
                BigDecimal performanceConversionRatio = new BigDecimal("0");
                if(oldFinishOrderProduct != null){
                    if(oldFinishOrderProduct.getPerformanceConversionRatio() != null){
                        performanceConversionRatio = oldFinishOrderProduct.getPerformanceConversionRatio();
                    }
                    if(oldFinishOrderProduct.getGradeMoney() != null ){
                        //业绩金额
                        BigDecimal gradeMoney = oldFinishOrderProduct.getGradeMoney();
                        if(gradeMoney != null && gradeMoney.compareTo(BigDecimal.ZERO) == 1){
                            //业绩金额-(回款金额*业绩换算比例)
                            gradeMoney = gradeMoney.subtract(arriveMoney.multiply(performanceConversionRatio));
                            fop.setGradeMoney(gradeMoney);
                        }
                    }
                }

                fop.setFinishOrderProductNum(finishOrderProductNum);
                fop.setProductStatus(productStatus);
                fop.setArriveTime(arriveTime);
                fop.setUpdatePeopleId(userAccount.getAccountId());
                fop.setUpdateTm(now);
                finishOrderProductDbService.updateArriveTimeAndOtherSelectiveInfo(fop);
//                log.info("流水审核通过，修改订单完成的产品表的业绩金额、回款时间、产品状态（" + productStatus + "）");
            }

            if(StringUtils.isNotBlank(productOrderId)){
                //订单最近到款录入时间
                Date returnMoneyCreateTm = null;
                //订单最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByOrderId(productOrderId, "create_tm desc");
                if(lastReturnMoney != null){
                    returnMoneyCreateTm = lastReturnMoney.getCreateTm();
                }

                CustomerProductOrder cpo = new CustomerProductOrder();

                if(oldCustomerProductOrder != null){
                    //已回款金额合计
                    BigDecimal paidBackAmount = oldCustomerProductOrder.getPaidBackAmount()==null ? new BigDecimal("0") : oldCustomerProductOrder.getPaidBackAmount();
                    //已回款金额合计减到款金额
                    paidBackAmount = paidBackAmount.subtract(arriveMoney);
                    cpo.setPaidBackAmount(paidBackAmount);

                    if(StringUtils.isBlank(contractId)){
//                        log.error("流水审核时找不到合同id");
                    }else{
                        if(oldCustomerContract == null){
//                            log.error("流水审核时找不到合同");
                        }else{
                            //合同总回款金额
                            BigDecimal contractTotalPaymentAmount = oldCustomerContract.getContractTotalPaymentAmount()==null ? new BigDecimal("0") : oldCustomerContract.getContractTotalPaymentAmount();
                            //合同总回款金额减到款金额
                            contractTotalPaymentAmount = contractTotalPaymentAmount.subtract(arriveMoney);

                            CustomerContract customerContract = new CustomerContract();
                            customerContract.setContractId(contractId);
                            customerContract.setContractStatus(contractStatus);
                            customerContract.setPaymentStatus(paymentStatus);
                            customerContract.setPaymentDate(returnMoneyCreateTm);
                            customerContract.setContractTotalPaymentAmount(contractTotalPaymentAmount);
                            customerContract.setUpdatePeopleId(userAccount.getAccountId());
                            customerContract.setUpdateTm(now);
                            customerContractDbService.updateArriveTimeAndOtherSelectiveInfo(customerContract);
//                            log.info("流水审核通过，修改合同表到款时间、合同总回款金额、合同状态（" + contractStatus + "）、回款状态（" + paymentStatus + "）");
                        }
                    }
                }
                cpo.setProductOrderId(productOrderId);
                cpo.setUpdatePeopleId(userAccount.getAccountId());
                cpo.setUpdateTm(now);
                cpo.setOrderStatus(orderStatus);
                cpo.setExchangeCodeSendingStatus(exchangeCodeSendingStatus);
//                if(arriveMoney.compareTo(new BigDecimal("0")) != 0) {//回款金额不等于0
//                    cpo.setOldOrder("-100");
//                }
                if(!"2".equals(orderStatus)){
                    cpo.setOldOrder("-100");
                }
                customerProductOrderDbService.updateOrderSelective(cpo);
//                log.info("流水审核通过，修改产品订单表的已回款金额合计及订单状态（" + orderStatus + "）");
            }

            if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(productOrderId) || StringUtils.isBlank(returnMoneyId)){
//                log.error("流水审核删除流水订单关联关系时，有空数据");
//                log.error("flowId:" + flowId + ", productOrderId:" + productOrderId + "returnMoneyId:" + returnMoneyId);
            }else{//删除流水订单关联关系
                BankOrder bo = new BankOrder();
                bo.setFlowId(flowId);
                bo.setOrderId(productOrderId);
                bo.setReturnMoneyId(returnMoneyId);
                bankOrderCustomMapper.delByFlowIdAndOrderIdAndReturnMoneyId(bo);
//                log.info("流水审核通过，删除流水订单关联关系");
            }

        }else if(bankFlowExamine.getExamineState() == 2){//流水审核拒绝后，修改回款记录的审核状态为正常，插入回款操作记录
            ReturnMoney rm = new ReturnMoney();
            rm.setReturnMoneyId(returnMoneyId);
            rm.setUpdateBy(userAccount.getAccountId());
            rm.setUpdateTm(now);
            rm.setExamState(0);
            returnMoneyDbservice.updateReturnMoney(rm);
//            log.info("流水审核拒绝，修改回款记录的审核状态为正常");
        }
        ReturnMoneyLog log = new ReturnMoneyLog();
        log.setReturnMoneyLogId(CommonUtils.getGUID());
        log.setFlowId(flowId);
        log.setReturnMoneyId(returnMoneyId);
        log.setCreatePeopleId(userAccount.getAccountId());
        log.setCreateTm(now);
        if(bankFlowExamine.getExamineState() == 1){//审核通过
            log.setNewData("备注：流水审核通过，删除回款记录，金额：" + arriveMoney);
            log.setOperatorType(2);  //操作类型 1修改 2删除 3退款 4关联 5调减
        }else{
            log.setNewData("备注：流水审核拒绝，回款记录审核状态由" + ((oldReturnMoney!=null && oldReturnMoney.getExamState()==1) ? "正在审核" : "正常") + "变为正常");
            log.setOperatorType(1);  //操作类型 1修改 2删除 3退款 4关联 5调减
        }
        //插入回款操作记录
        returnMoneyLogDbService.addReturnMoneyLog(log);

        bankFlowExamine.setExaminePeopleId(userAccount.getAccountId());
        bankFlowExamine.setExamineTime(now);
        bankFlowExamineDbService.updateByPrimaryKeySelective(bankFlowExamine);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public synchronized DataResponse examineByPay(BankFlowExamine bankFlowExamine, BankFlowExamine oldExamine) {
        //银行流水记录id
        String flowId = oldExamine.getRelationId();
        //原银行流水记录
        BankFlow oldBankFlow = bankFlowDbService.selectByFlowId(flowId);
//        if(oldBankFlow == null){
//            log.error("流水审核时找不到流水记录");
//        }
        //充值id
        String customerPayId = oldExamine.getCustomerPayId();

        //充值记录
        CustomerPay oldCustomerPay = customerPayDbService.selectByPrimaryKey(customerPayId);
//        if(oldCustomerPay == null){
//            log.error("流水审核时找不到充值记录" + customerPayId);
//        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Date now = new Date();

        //操作记录
        ReturnMoneyLog rmLog = new ReturnMoneyLog();

        //流水审核通过后
        //客户充值表确认收款弹框里的除到款金额外其他内容清空，payStatus改为0，插入充值操作记录
        //修改客户钱包余额
        if(bankFlowExamine.getExamineState() == 1){

            if(oldCustomerPay != null){
                //充值金额
                BigDecimal payMoney = oldCustomerPay.getPayMoney()==null ? new BigDecimal("0") : oldCustomerPay.getPayMoney();
                //客户id
                String customerId = oldCustomerPay.getCustomerId();
                //客户信息
                Customer oldCustomer = customerDbService.selectCustomerById(customerId);
                if(oldCustomerPay == null){
//                    log.error("流水审核时找不到客户信息" + customerId);
                }else{
                    //客户钱包余额
                    BigDecimal customerWallet = oldCustomer.getCustomerWallet()==null ? new BigDecimal("0") : oldCustomer.getCustomerWallet();
                    //客户钱包余额减充值金额
                    customerWallet = customerWallet.subtract(payMoney);
                    Customer c = new Customer();
                    c.setCustomerId(customerId);
                    c.setCustomerWallet(customerWallet);
                    c.setUpdatePeopleId(userAccount.getAccountId());
                    c.setUpdateTm(now);
                    customerDbService.updateByPrimaryKeySelective(c);
//                    log.info("流水审核通过（充值码），修改客户钱包余额");

                    CustomerPay cp = new CustomerPay();
                    cp.setChsCustomerPayId(customerPayId);
                    cp.setPayStatus(0);
                    cp.setExamState(0);
                    cp.setUpdatePeopleId(userAccount.getAccountId());
                    cp.setUpdateTm(now);
                    customerPayDbService.updatePayInfo(cp);
//                    log.info("流水审核通过（充值码），修改充值记录的收款相关信息为空，收款确认状态为未确认，审核状态为正常");

                    String arriveMethod = oldCustomerPay.getArriveMethod()==null?null:(oldCustomerPay.getArriveMethod()==0?"银行回款":(oldCustomerPay.getArriveMethod()==1?"现金":(oldCustomerPay.getArriveMethod()==2?"线上支付":"")));
                    String arriveAccountType = null;
                    if(oldCustomerPay.getArriveAccountType() != null){
                        if(oldCustomerPay.getArriveAccountType() == 0){
                            arriveAccountType = "分公司";
                        }else if(oldCustomerPay.getArriveAccountType() == 1){
                            arriveAccountType = "北京财税研究院";
                        }else if(oldCustomerPay.getArriveAccountType() == 2){
                            arriveAccountType = "大成方略网络科技有限公司";
                        }else if(oldCustomerPay.getArriveAccountType() == 3){
                            arriveAccountType = "北京大成方略财务顾问有限公司";
                        }else if(oldCustomerPay.getArriveAccountType() == 4){
                            arriveAccountType = "北京大成方略纳税人俱乐部有限公司";
                        }else if(oldCustomerPay.getArriveAccountType() == 5){
                            arriveAccountType = "大成方略纳税人俱乐部股份有限公司";
                        }else{
                            arriveAccountType = oldCustomerPay.getArriveAccountType() + "";
                        }
                    }
                    String payStatus = oldCustomerPay.getPayStatus()==null?null:(oldCustomerPay.getPayStatus()==0?"未确认":(oldCustomerPay.getPayStatus()==1?"已确认":""));
                    String examState = (oldCustomerPay!=null && oldCustomerPay.getExamState()==1) ? "正在审核" : "正常";

//                    rmLog.setFormerData("充值码收款信息，付款单位：" + oldCustomerPay.getPaymentUnit() + "，到款日期：" + DateUtils.formatDate(oldCustomerPay.getPaymentDate())
//                            + "，到款方式：" + arriveMethod + "，付款账号：" + oldCustomerPay.getPaymentAccount() + "，付款银行：" + oldCustomerPay.getPaymentBank()
//                            + "，流水号：" + oldCustomerPay.getPaymentSerial() + "，到款账号类型：" + arriveAccountType + "，备注" + oldCustomerPay.getRemark()
//                            + "，收款确认状态：" + payStatus + "，审核状态：" + examState);


                    StringBuilder formerData = new StringBuilder();
                    formerData.append("充值码收款信息，付款单位：");
                    formerData.append(oldCustomerPay.getPaymentUnit());
                    formerData.append("，到款日期：");
                    formerData.append(DateUtils.formatDate(oldCustomerPay.getPaymentDate()));
                    formerData.append("，到款方式：");
                    formerData.append(arriveMethod);
                    formerData.append("，付款账号：");
                    formerData.append(oldCustomerPay.getPaymentAccount());
                    formerData.append("，付款银行：");
                    formerData.append(oldCustomerPay.getPaymentBank());
                    formerData.append("，流水号：");
                    formerData.append(oldCustomerPay.getPaymentSerial());
                    formerData.append("，到款账号类型：");
                    formerData.append(arriveAccountType);
                    formerData.append("，到款单位名称：");
                    formerData.append(oldCustomerPay.getArriveUnitName());
                    formerData.append("，备注：");
                    formerData.append(oldCustomerPay.getRemark());
                    formerData.append("，收款确认状态：");
                    formerData.append(payStatus);
                    formerData.append("，审核状态：");
                    formerData.append(examState);
                    rmLog.setFormerData(formerData.toString());
                    rmLog.setNewData("备注：流水审核通过（充值码），修改充值记录的收款相关信息为空，收款确认状态为未确认，审核状态为正常");

                    if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(customerPayId)){
//                        log.error("流水审核删除流水订单关联关系时，有空数据");
//                        log.error("flowId:" + flowId + ", customerPayId:" + customerPayId);
                    }else{//删除流水订单关联关系
                        BankOrder bo = new BankOrder();
                        bo.setFlowId(flowId);
                        bo.setCustomerPayId(customerPayId);
                        bankOrderCustomMapper.delByFlowIdAndCustomerPayId(bo);
//                        log.info("流水审核通过（充值码），删除流水订单关联关系");
                    }

                    //贷方金额
                    BigDecimal creditMoney = oldBankFlow.getCreditMoney()==null?new BigDecimal("0"):oldBankFlow.getCreditMoney();
                    //可用金额
                    BigDecimal availableAmount = oldBankFlow.getAvailableAmount()==null?new BigDecimal("0"):oldBankFlow.getAvailableAmount();
                    //已用金额
                    BigDecimal usedAmount = oldBankFlow.getUsedAmount()==null?new BigDecimal("0"):oldBankFlow.getUsedAmount();
                    //可用金额加充值金额
                    availableAmount = availableAmount.add(payMoney);
                    //已用金额减充值金额
                    usedAmount = usedAmount.subtract(payMoney);

                    BankFlow bf = new BankFlow();
                    bf.setFlowId(flowId);
                    bf.setUpdateTime(now);
                    bf.setAvailableAmount(availableAmount);
                    bf.setUsedAmount(usedAmount);
                    //若贷方金额等于可用金额，关联状态改为N未关联，否则改为B部分关联
                    if(creditMoney.compareTo(availableAmount) == 0){
                        bf.setRelationState("N");
                    }else{
                        bf.setRelationState("B");
                    }
                    //修改可用金额、已用金额、关联状态
                    bankFlowDbService.updateByPrimaryKeySelective(bf);
//                    log.info("流水审核通过（充值码），修改银行流水记录的可用金额、已用金额、关联状态");
                }
            }
        }else if(bankFlowExamine.getExamineState() == 2){//流水审核拒绝后，修改充值记录的审核状态为正常，插入充值操作记录
            CustomerPay cp = new CustomerPay();
            cp.setChsCustomerPayId(customerPayId);
            cp.setExamState(0);
            cp.setUpdatePeopleId(userAccount.getAccountId());
            cp.setUpdateTm(now);
            customerPayDbService.updateCustomerPay(cp);
//            log.info("流水审核拒绝（充值码），修改充值记录的审核状态为正常");
            rmLog.setNewData("备注：流水审核拒绝（充值码），充值码审核状态由" + ((oldCustomerPay!=null && oldCustomerPay.getExamState()==1) ? "正在审核" : "正常") + "变为正常");
        }

        rmLog.setReturnMoneyLogId(CommonUtils.getGUID());
        rmLog.setFlowId(flowId);
        rmLog.setCustomerPayId(customerPayId);
        rmLog.setCreatePeopleId(userAccount.getAccountId());
        rmLog.setCreateTm(now);
        rmLog.setOperatorType(1);  //操作类型 1修改 2删除 3退款 4关联 5调减
        //插入充值操作记录
        returnMoneyLogDbService.addReturnMoneyLog(rmLog);

        bankFlowExamine.setExaminePeopleId(userAccount.getAccountId());
        bankFlowExamine.setExamineTime(now);
        bankFlowExamineDbService.updateByPrimaryKeySelective(bankFlowExamine);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public synchronized DataResponse examineForPrepareReturn(BankFlowExamine bankFlowExamine, BankFlowExamine oldExamine) {
        //银行流水记录id
        String flowId = oldExamine.getRelationId();
        //原银行流水记录
        BankFlow oldBankFlow = bankFlowDbService.selectByFlowId(flowId);
//        if(oldBankFlow == null){
//            log.error("预回款审核时找不到流水记录");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }
        //回款id
        String returnMoneyId = oldExamine.getReturnMoneyId();
//        if(StringUtils.isBlank(returnMoneyId)){
//            log.error("预回款审核时找不到回款id");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }
        //原回款记录
        ReturnMoneyVO oldReturnMoney = returnMoneyDbservice.getReturnMoenyInfoById(returnMoneyId);
//        if(oldReturnMoney == null){
//            log.error("预回款审核时找不到回款记录");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }

        //订单id
        String productOrderId = oldExamine.getProductOrderId();
//        if(StringUtils.isBlank(productOrderId)){
//            log.error("预回款审核时找不到订单id");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }

        //到款金额
        BigDecimal arriveMoney = (oldReturnMoney==null || oldReturnMoney.getArriveMoney()==null) ? new BigDecimal("0") : oldReturnMoney.getArriveMoney();

        //产品号
        String finishOrderProductNum = oldExamine.getFinishOrderProductNum();
        FinishOrderProductVO oldFinishOrderProduct = finishOrderProductDbService.selectFinishOrderProductByNumber(finishOrderProductNum);
        //产品订单
        CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Date now = new Date();

        //预回款审核不通过，先修改银行流水的可用金额、已用金额、关联状态，删除回款记录
        if(bankFlowExamine.getExamineState() == 2) {
            if(StringUtils.isNoneBlank(returnMoneyId)) {
                if (oldReturnMoney != null && oldBankFlow != null) {
                    //贷方金额
                    BigDecimal creditMoney = oldBankFlow.getCreditMoney() == null ? new BigDecimal("0") : oldBankFlow.getCreditMoney();
                    //可用金额
                    BigDecimal availableAmount = oldBankFlow.getAvailableAmount() == null ? new BigDecimal("0") : oldBankFlow.getAvailableAmount();
                    //已用金额
                    BigDecimal usedAmount = oldBankFlow.getUsedAmount() == null ? new BigDecimal("0") : oldBankFlow.getUsedAmount();
                    //可用金额加到款金额
                    availableAmount = availableAmount.add(arriveMoney);
                    //已用金额减到款金额
                    usedAmount = usedAmount.subtract(arriveMoney);

                    BankFlow bf = new BankFlow();
                    bf.setFlowId(flowId);
                    bf.setUpdateTime(now);
                    bf.setAvailableAmount(availableAmount);
                    bf.setUsedAmount(usedAmount);
                    //若贷方金额等于可用金额，关联状态改为N未关联，否则改为B部分关联
                    if (creditMoney.compareTo(availableAmount) == 0) {
                        bf.setRelationState("N");
                    } else {
                        bf.setRelationState("B");
                    }
                    //修改可用金额、已用金额、关联状态
                    bankFlowDbService.updateByPrimaryKeySelective(bf);
        //            log.info("预回款审核拒绝，修改银行流水记录的可用金额、已用金额、关联状态");
                }
                ReturnMoney rm = new ReturnMoney();
                rm.setReturnMoneyId(returnMoneyId);
                rm.setUpdateBy(userAccount.getAccountId());
                rm.setDelFlag(1);
                rm.setUpdateTm(now);
                //删除回款
                returnMoneyDbservice.updateReturnMoney(rm);
    //            log.info("预回款审核拒绝，删除回款");
            }
        }else if(bankFlowExamine.getExamineState() == 1) {//预回款审核通过后，先修改回款记录的回款状态为正常
            ReturnMoney rm = new ReturnMoney();
            rm.setReturnMoneyId(returnMoneyId);
            rm.setUpdateBy(userAccount.getAccountId());
            rm.setUpdateTm(now);
            rm.setExamState(0);
            rm.setReturnStatus(1);
            returnMoneyDbservice.updateReturnMoney(rm);
//            log.info("预回款审核通过，修改回款记录的回款状态为正常");
        }

        //合同id
        String contractId = oldCustomerProductOrder!=null ? oldCustomerProductOrder.getContractId() : null;
        //合同
        CustomerContract oldCustomerContract = customerContractDbService.selectContractById(contractId);

        //各表状态
        Map<String, String> status = this.getStatus(productOrderId, finishOrderProductNum, oldFinishOrderProduct, oldCustomerContract);

        //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
        String productStatus = status.get("productStatus");
        //订单状态，1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）;5:预回款
        String orderStatus = status.get("orderStatus");
        //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
        String paymentStatus = status.get("paymentStatus");
        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        String contractStatus = status.get("contractStatus");

        //审核不管通不通过，都要修改回款记录表（若删除表则不需要改）、流水关联表（若删除表则不需要改）、finish表、订单表、合同表的回款状态从预回款改为未回款或部分回款或已回款（金额为0的情况）或正常

        //预回款审核不通过
        //删除回款记录，插入回款操作记录-----------------------代码在上面
        //修改银行流水的可用金额、已用金额、关联状态-----------------------代码在上面
        //修改订单完成的产品表的业绩金额、回款时间、产品状态（未回款、部分回款或预回款）
        //修改产品订单表的订单状态（未回款、部分回款或预回款），订单状态从2<已完成>到其他状态则卡作废，修改已回款金额合计
        //修改合同表到款时间、合同总回款金额、合同状态（订单状态为预回款，则合同也为预回款，订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>）
        if(bankFlowExamine.getExamineState() == 2){
            if(StringUtils.isBlank(finishOrderProductNum)){
//                log.error("预回款审核时找不到产品号");
            }else{
                //产品最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByFinishOrderProductNum(finishOrderProductNum);
                //产品最近到款时间
                Date arriveTime = null;
                if(lastReturnMoney != null){
                    arriveTime = lastReturnMoney.getArriveTime();
                }

                //订单完成的产品
                FinishOrderProduct fop = new FinishOrderProduct();

                //业绩换算比例
                BigDecimal performanceConversionRatio = new BigDecimal("0");
                if(oldFinishOrderProduct != null){
                    if(oldFinishOrderProduct.getPerformanceConversionRatio() != null){
                        performanceConversionRatio = oldFinishOrderProduct.getPerformanceConversionRatio();
                    }
                    if(oldFinishOrderProduct.getGradeMoney() != null ){
                        //业绩金额
                        BigDecimal gradeMoney = oldFinishOrderProduct.getGradeMoney();
                        if(gradeMoney != null && gradeMoney.compareTo(BigDecimal.ZERO) == 1){
                            //业绩金额-(回款金额*业绩换算比例)
                            gradeMoney = gradeMoney.subtract(arriveMoney.multiply(performanceConversionRatio));
                            fop.setGradeMoney(gradeMoney);
                        }
                    }
                }

                fop.setFinishOrderProductNum(finishOrderProductNum);
                fop.setProductStatus(productStatus);
                fop.setArriveTime(arriveTime);
                fop.setUpdatePeopleId(userAccount.getAccountId());
                fop.setUpdateTm(now);
                finishOrderProductDbService.updateArriveTimeAndOtherSelectiveInfo(fop);
//                log.info("预回款审核拒绝，修改订单完成的产品表的业绩金额、回款时间、产品状态（" + productStatus + "）");
            }

            if(StringUtils.isNotBlank(productOrderId)){
                //订单最近到款录入时间
                Date returnMoneyCreateTm = null;
                //订单最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByOrderId(productOrderId, "create_tm desc");
                if(lastReturnMoney != null){
                    returnMoneyCreateTm = lastReturnMoney.getCreateTm();
                }
                CustomerProductOrder cpo = new CustomerProductOrder();

                //产品订单
                if(oldCustomerProductOrder != null){
                    //已回款金额合计
                    BigDecimal paidBackAmount = oldCustomerProductOrder.getPaidBackAmount()==null ? new BigDecimal("0") : oldCustomerProductOrder.getPaidBackAmount();
                    //已回款金额合计减到款金额
                    paidBackAmount = paidBackAmount.subtract(arriveMoney);
                    cpo.setPaidBackAmount(paidBackAmount);

                    if(StringUtils.isBlank(contractId)){
//                        log.error("流水审核时找不到合同id");
                    }else{
                        if(oldCustomerContract == null){
    //                        log.error("预回款审核时找不到合同");
                        }else{
                            //合同总回款金额
                            BigDecimal contractTotalPaymentAmount = oldCustomerContract.getContractTotalPaymentAmount()==null ? new BigDecimal("0") : oldCustomerContract.getContractTotalPaymentAmount();
                            //合同总回款金额减到款金额
                            contractTotalPaymentAmount = contractTotalPaymentAmount.subtract(arriveMoney);

                            CustomerContract customerContract = new CustomerContract();
                            customerContract.setContractId(contractId);
                            customerContract.setContractStatus(contractStatus);
                            customerContract.setPaymentStatus(paymentStatus);
                            customerContract.setPaymentDate(returnMoneyCreateTm);
                            customerContract.setContractTotalPaymentAmount(contractTotalPaymentAmount);
                            customerContract.setUpdatePeopleId(userAccount.getAccountId());
                            customerContract.setUpdateTm(now);
                            customerContractDbService.updateArriveTimeAndOtherSelectiveInfo(customerContract);
    //                        log.info("预回款审核拒绝，修改合同表到款时间、合同总回款金额、合同状态（" + contractStatus + "）、回款状态（" + paymentStatus + "）");
                        }
                    }
                }

                cpo.setProductOrderId(productOrderId);
                cpo.setUpdatePeopleId(userAccount.getAccountId());
                cpo.setUpdateTm(now);
                cpo.setOrderStatus(orderStatus);
//                if(arriveMoney.compareTo(new BigDecimal("0")) != 0) {//回款金额不等于0
//                    cpo.setOldOrder("-100");
//                }
                if(!"2".equals(orderStatus)){
                    cpo.setOldOrder("-100");
                }
                customerProductOrderDbService.updateOrderSelective(cpo);
    //            log.info("预回款审核拒绝，修改产品订单表的已回款金额合计及订单状态（" + orderStatus + "）");
            }

            if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(productOrderId) || StringUtils.isBlank(returnMoneyId)){
//                log.error("预回款审核删除流水订单关联关系时，有空数据");
//                log.error("flowId:" + flowId + ", productOrderId:" + productOrderId + "returnMoneyId:" + returnMoneyId);
            }else{//删除流水订单关联关系
                BankOrder bo = new BankOrder();
                bo.setFlowId(flowId);
                bo.setOrderId(productOrderId);
                bo.setReturnMoneyId(returnMoneyId);
                bankOrderCustomMapper.delByFlowIdAndOrderIdAndReturnMoneyId(bo);
//                log.info("预回款审核拒绝，删除流水订单关联关系");
            }
        }else if(bankFlowExamine.getExamineState() == 1){//预回款审核通过后，订单状态从其他状态到2<已完成>则发放会员卡，修改回款记录的回款状态为正常（代码在上面），插入回款操作记录
            if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(productOrderId) || StringUtils.isBlank(returnMoneyId)){
//                log.error("预回款审核删除流水订单关联关系时，有空数据");
//                log.error("flowId:" + flowId + ", productOrderId:" + productOrderId + "returnMoneyId:" + returnMoneyId);
            }else{//修改流水订单关联表的订单回款状态
                BankOrder bo = new BankOrder();
                bo.setFlowId(flowId);
                bo.setOrderId(productOrderId);
                bo.setReturnMoneyId(returnMoneyId);
                bo.setReturnStatus(1);
                bankOrderCustomMapper.updateByFlowIdAndOrderIdAndReturnMoneyId(bo);
//                log.info("预回款审核通过，修改流水订单关联表的订单回款状态为正常");
            }

            if(oldFinishOrderProduct != null){
                //订单完成的产品
                FinishOrderProduct fop = new FinishOrderProduct();
                fop.setFinishOrderProductId(oldFinishOrderProduct.getFinishOrderProductId());
                fop.setProductStatus(productStatus);
                fop.setUpdatePeopleId(userAccount.getAccountId());
                fop.setUpdateTm(now);
                finishOrderProductDbService.updateFinishOrderProduct(fop);
//                log.info("预回款审核通过，修改订单完成的产品表的产品状态（" + productStatus + "）");
            }

            CustomerProductOrder cpo = new CustomerProductOrder();
            cpo.setProductOrderId(productOrderId);
            cpo.setUpdatePeopleId(userAccount.getAccountId());
            cpo.setUpdateTm(now);
            cpo.setOrderStatus(orderStatus);
//            if(!"2".equals(orderStatus)){
//                cpo.setOldOrder("-100");
//            }

            //订单状态从其他状态到2<已完成>，发放会员卡，修改订单完成时间
            if(oldCustomerProductOrder != null && !"2".equals(oldCustomerProductOrder.getOrderStatus()) && "2".equals(orderStatus)){
                cpo.setOrderCompleteTm(now);
                customerProductOrderDbService.updateOrderSelective(cpo);
//            log.info("预回款审核通过，修改产品订单表的订单状态（" + orderStatus + "）");
                try{
                    returnMoneyService.hairpin(productOrderId);
                }catch (ParseException e){
                    e.printStackTrace();
                }
            }else{
                customerProductOrderDbService.updateOrderSelective(cpo);
//            log.info("预回款审核通过，修改产品订单表的订单状态（" + orderStatus + "）");
            }

            CustomerContract customerContract = new CustomerContract();
            customerContract.setContractId(oldCustomerProductOrder.getContractId());
            customerContract.setContractStatus(contractStatus);
            customerContract.setPaymentStatus(paymentStatus);
            customerContract.setUpdatePeopleId(userAccount.getAccountId());
            customerContract.setUpdateTm(now);
            customerContractDbService.updateCustomerContract(customerContract);
//            log.info("预回款审核通过，修改合同表合同状态（" + contractStatus + "）、回款状态（" + paymentStatus + "）");
        }

        ReturnMoneyLog log = new ReturnMoneyLog();
        log.setReturnMoneyLogId(CommonUtils.getGUID());
        log.setFlowId(flowId);
        log.setReturnMoneyId(returnMoneyId);
        log.setCreatePeopleId(userAccount.getAccountId());
        log.setCreateTm(now);
        if(bankFlowExamine.getExamineState() == 2){//审核拒绝
            log.setNewData("备注：预回款审核拒绝，删除回款记录，金额：" + arriveMoney);
            log.setOperatorType(2);  //操作类型 1修改 2删除 3退款 4关联 5调减
        }else{//审核通过
            log.setNewData("备注：预回款审核通过，回款记录回款状态由" + ((oldReturnMoney.getReturnStatus()!=null && oldReturnMoney.getReturnStatus()==0) ? "预回款" : "正常") + "变为正常");
            log.setOperatorType(1);  //操作类型 1修改 2删除 3退款 4关联 5调减
        }
        //插入回款操作记录
        returnMoneyLogDbService.addReturnMoneyLog(log);

        bankFlowExamine.setExaminePeopleId(userAccount.getAccountId());
        bankFlowExamine.setExamineTime(now);
        bankFlowExamineDbService.updateByPrimaryKeySelective(bankFlowExamine);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public Map<String, String> getStatus(String productOrderId, String finishOrderProductNum, FinishOrderProductVO oldFinishOrderProduct, CustomerContract oldCustomerContract){
        //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
        String productStatus = null;
        //订单状态，1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）;5:预回款
        String orderStatus = null;
        //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
        String paymentStatus = null;
        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        String contractStatus = "1";

        //订单回款记录
        List<ReturnMoneyVO> returnMoneyVOList = returnMoneyDbservice.selectListByOrderId(productOrderId);
        //产品回款
        BigDecimal productReturn = new BigDecimal("0");
        //订单回款
        BigDecimal orderReturn = new BigDecimal("0");

        for(ReturnMoneyVO rmVO : returnMoneyVOList){
            if(rmVO.getArriveMoney() != null){
                if(rmVO.getReturnStatus() != null && rmVO.getReturnStatus() == 1){//回款状态为正常
                    if(finishOrderProductNum != null && finishOrderProductNum.equals(rmVO.getFinishOrderProductNum())){
                        productReturn = productReturn.add(rmVO.getArriveMoney());
                    }
                    orderReturn = orderReturn.add(rmVO.getArriveMoney());
                }else{
                    if(rmVO.getArriveMoney().compareTo(new BigDecimal("0")) != 0){//回款状态为预回款且回款金额不等于0
                        orderStatus = "5";//订单预回款
                        paymentStatus = "4";//合同预回款
                        if(finishOrderProductNum != null && finishOrderProductNum.equals(rmVO.getFinishOrderProductNum())){
                            productStatus = "6";//产品预回款
                            break;
                        }
                    }
                }
            }
        }

        if(StringUtils.isBlank(finishOrderProductNum)){
//            log.error("预回款审核时找不到产品号");
        }else{
            if(oldFinishOrderProduct != null){
                //产品成交价
                BigDecimal productFinalPrice = oldFinishOrderProduct.getProductFinalPrice();
                if(productFinalPrice != null){
                    //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
                    if(!"6".equals(productStatus)){
                        if(productReturn.compareTo(BigDecimal.ZERO) == 0){//产品回款为0，为未回款
                            productStatus = "0";
                        }else if(productReturn.compareTo(productFinalPrice) >= 0){//产品回款大于或等于产品成交价，为已回款
                            productStatus = "3";
                        }else{//部分回款
                            productStatus = "2";
                        }
                    }
                }

            }
        }

        if(oldCustomerContract == null){
//            log.error("预回款审核时找不到合同");
        }else{
            //合同应收款
            BigDecimal contractReceivables = oldCustomerContract.getContractReceivables();
            if(contractReceivables != null){
                //订单状态，1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）;5:预回款
                //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
                if(!"5".equals(orderStatus)){
                    if(orderReturn.compareTo(BigDecimal.ZERO) == 0){//订单回款为0，为未回款
                        orderStatus = "1";
                        paymentStatus = "0";
                    }else if(orderReturn.compareTo(contractReceivables) >= 0){//订单回款大于或等于合同应收款，为已回款
                        orderStatus = "2";
                        paymentStatus = "1";
                    }else{//部分回款
                        orderStatus = "4";
                        paymentStatus = "3";
                    }
                }
            }
        }
        //订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>
        if("2".equals(orderStatus)){
            contractStatus = "2";
        }

        Map<String, String> map = new HashMap<>();
        map.put("productStatus", productStatus);
        map.put("orderStatus", orderStatus);
        map.put("paymentStatus", paymentStatus);
        map.put("contractStatus", contractStatus);

        return map;
    }

    @Override
    public DhPageInfo<FinishOrderProductVO> selectProductPageList(Integer pageIndex, Integer pageSize, BankFlowExamineQO bankFlowExamineQO) {

        BankFlowExamine examine = bankFlowExamineDbService.selectByExamineId(bankFlowExamineQO.getExamineId());

        if(examine != null){
            if(examine.getExamineType() == 1){
                return finishOrderProductService.selectOrderFinishProduct(examine.getProductOrderId(), pageIndex, pageSize);
            }
        }

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer type = null;
        CustomerProductOrder order = customerProductOrderDbService.selectProductOrderById(examine.getProductOrderId());
        if (Objects.nonNull(order.getOrderSurcharge())
                && new BigDecimal("0").compareTo(order.getOrderSurcharge()) == -1){
            type = 1;
        }

        List<FinishOrderProductVO> resultList = bankFlowExamineDbService.selectProductList(bankFlowExamineQO);
        for (int i=0;i<resultList.size();i++){
            BigDecimal big = new BigDecimal("0");
            if (Objects.isNull(resultList.get(i).getFinishOrderProductId()) && type == 1
                    && "附加费用".equals(resultList.get(i).getProductName()) && "0001".equals(resultList.get(i).getFinishOrderProductNum())){
                big = returnMoneyDbservice.selectOrderSurchargeCount(resultList.get(i).getProductOrderId());
                BigDecimal productFinalPrice = order.getOrderSurcharge();
                resultList.get(i).setProductFinalPrice(productFinalPrice);

            }else {
                if(examine != null && StringUtils.isNoneBlank(examine.getProductOrderId())){
                    big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(resultList.get(i).getFinishOrderProductId(), examine.getProductOrderId());
                }
            }
            if (Objects.isNull(big)){
                big = new BigDecimal("0");
            }
            resultList.get(i).setPaidMoney(big);
            if(resultList.get(i).getProductFinalPrice() == null){
                resultList.get(i).setProductFinalPrice(new BigDecimal("0"));
            }
            resultList.get(i).setResidueMoney(resultList.get(i).getProductFinalPrice().subtract(big));
        }

        PageInfo<FinishOrderProductVO> pageInfo=new PageInfo<>(resultList);
        return new DhPageInfo<FinishOrderProductVO>(pageInfo,resultList);
    }

    @Override
    public DhPageInfo<ReturnMoneyVO> selectReturnMoneyPageList(Integer pageIndex, Integer pageSize, BankFlowExamineQO bankFlowExamineQO) {

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<ReturnMoneyVO> resultList=bankFlowExamineDbService.selectReturnMoneyList(bankFlowExamineQO);

        PageInfo<ReturnMoneyVO> pageInfo=new PageInfo<>(resultList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo,resultList);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse relieveRelationByProductOrderId(BankFlowExamine bankFlowExamine) {
        if(StringUtils.isBlank(bankFlowExamine.getProductOrderId())){
            return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }

        //产品订单
        CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(bankFlowExamine.getProductOrderId());
        if(oldCustomerProductOrder == null){
            return new DhResponse(ResponseCodeEnum.CUSTOMER_PRODUCT_ORDER_NOT_EXIST.getResponseCode());
        }

        if(oldCustomerProductOrder.getExamineState() != null && oldCustomerProductOrder.getExamineState() == 1){
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_EXAMINE_STATE_1.getResponseCode());
        }

        if("5".equals(oldCustomerProductOrder.getOrderStatus())){//预回款订单不能解除关联
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_PRE_RETURN.getResponseCode());
        }

        //订单回款记录
        List<ReturnMoneyVO> returnMoneyVOList = returnMoneyDbservice.selectListByOrderId(bankFlowExamine.getProductOrderId());

        if(returnMoneyVOList.size() == 0){//解除关联失败：没有回款记录
            return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_NOT_RETURN_MONEY.getResponseCode());
        }

        for(ReturnMoneyVO vo : returnMoneyVOList){
            if(vo.getBankOrderId() == null){//解除关联失败：有未关联流水的回款记录
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_NOT_ALL_HAS_SERIAL.getResponseCode());
            }
            if(vo.getReturnStatus() != null && vo.getReturnStatus() == 0){//解除关联失败：有预回款记录
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_HAS_PRE_RETURN.getResponseCode());
            }
            if(vo.getCloseStatus() != null && vo.getCloseStatus() == 1){//解除关联失败：有封账的回款记录
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_RELIEVE_RELATION_FAIL_HAS_CLOSE.getResponseCode());
            }
        }

        Date now = new Date();

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        BankFlowExamine examine = new BankFlowExamine();
        examine.setExamineId(UUID.randomUUID().toString().replaceAll("-", ""));
        examine.setProductOrderId(bankFlowExamine.getProductOrderId());
        examine.setRelationReason(bankFlowExamine.getRelationReason());
        examine.setApplyPeopleId(userAccount.getAccountId());
        examine.setApplyTime(now);
        examine.setCompanyId(userAccount.getCompanyId());
        examine.setExamineType((short) 1);
        bankFlowExamineDbService.insertSelective(examine);

        CustomerProductOrder cpo = new CustomerProductOrder();
        cpo.setProductOrderId(bankFlowExamine.getProductOrderId());
        cpo.setExamineState((short) 1);
        cpo.setUpdatePeopleId(userAccount.getAccountId());
        cpo.setUpdateTm(now);
        customerProductOrderDbService.updateByPrimaryKeySelective(cpo);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public Map getDetails(String examineId) {
        BankFlowExamine examine = bankFlowExamineDbService.selectByExamineId(examineId);
        if(examine == null){
            return null;
        }

        Map data = new HashMap();

//        FinanceProductOderInfoVO vo = customerProductOrderService.financeProductOderInfo(examine.getProductOrderId(), null);

        //优先查正常产品
        FinanceProductOderInfoVO vo =customerProductOrderDbService.getFinanceProductOderInfo(examine.getProductOrderId(), null,1);
        if (Objects.isNull(vo)){
            vo =customerProductOrderDbService.getFinanceProductOderInfo(examine.getProductOrderId(), null,null);
        }
        if (Objects.nonNull(vo) && Objects.nonNull(vo.getOrderActualTotalAmount()) && Objects.nonNull(vo.getReturnMoneyAmount())){
            vo.setResidueMoneyAmount(vo.getOrderActualTotalAmount().subtract(vo.getReturnMoneyAmount()));
        }

        CustomerContractDetailVO customerContractDetailVO = customerContractService.selectCustomerContractVODetail(vo.getContractId());
        if (Objects.nonNull(customerContractDetailVO)){
            //隐藏客户信息
            customerContractDetailVO.setContactName(null);
            customerContractDetailVO.setContactDetails(null);
            customerContractDetailVO.setCustomerEmail(null);
        }

        data.put("productName", examine.getProductName());  //产品名称
        data.put("finishOrderProductNum", examine.getFinishOrderProductNum());  //产品号
        data.put("relationReason", examine.getRelationReason());  //解除关联备注
        data.put("examineInfo", examine.getExamineInfo());  //审核说明
        data.put("examineState", examine.getExamineState());  //审核状态
        data.put("productOrderId", examine.getProductOrderId());  //订单id

        if(customerContractDetailVO != null){
            data.put("contractId", customerContractDetailVO.getContractId());
            data.put("contractNumber", customerContractDetailVO.getContractNumber());  //合同编号
            data.put("contractType", customerContractDetailVO.getContractType());  //合同类型

            if(customerContractDetailVO.getContractStartDate() != null){
                data.put("contractStartDate", DateUtil.formatDate(customerContractDetailVO.getContractStartDate()));  //合同开始时间
            }
            if(customerContractDetailVO.getContractEndDate() != null){
                data.put("contractEndDate", DateUtil.formatDate(customerContractDetailVO.getContractEndDate()));  //合同结束时间
            }
        }

        if(vo != null){
            data.put("orderNumber", vo.getOrderNumber());  //订单编号
            data.put("orderStatus", vo.getOrderStatus());  //订单状态
            data.put("orderActualTotalAmount", vo.getOrderActualTotalAmount()!=null ? vo.getOrderActualTotalAmount().toString() : "");  //订单总金额
            data.put("returnMoneyAmount", vo.getReturnMoneyAmount()!=null ? vo.getReturnMoneyAmount().toString() : "");  //订单当前回款
            data.put("residueMoneyAmount", vo.getResidueMoneyAmount()!=null ? vo.getResidueMoneyAmount().toString() : "");  //订单当前尾款
            data.put("createPeopleName", vo.getCreatePeopleName());  //订单所有人
            data.put("companyName", vo.getCompanyName());  //所属分公司
            data.put("customerName", vo.getCustomerName());  //客户名称
            data.put("createTm", vo.getCreateTm());  //订单创建时间
        }


        FinishOrderProductVO finishOrderProductVO = finishOrderProductDbService.selectFinishOrderProductByNumber(examine.getFinishOrderProductNum());
        CustomerProductOrder order = customerProductOrderDbService.selectProductOrderById(examine.getProductOrderId());

        if(finishOrderProductVO != null && order != null){
            Integer type = null;
            if (Objects.nonNull(order.getOrderSurcharge())
                    && new BigDecimal("0").compareTo(order.getOrderSurcharge()) == -1){
                type = 1;
            }
            BigDecimal big = new BigDecimal("0");
            if (Objects.isNull(finishOrderProductVO.getFinishOrderProductId()) && type == 1
                    && "附加费用".equals(finishOrderProductVO.getProductName()) && "0001".equals(finishOrderProductVO.getFinishOrderProductNum())){
                big = returnMoneyDbservice.selectOrderSurchargeCount(finishOrderProductVO.getProductOrderId());
            }else {
                big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(finishOrderProductVO.getFinishOrderProductId(), examine.getProductOrderId());
            }
            if (Objects.isNull(big)){
                big = new BigDecimal("0");
            }
            finishOrderProductVO.setPaidMoney(big);
            finishOrderProductVO.setResidueMoney((finishOrderProductVO.getProductFinalPrice()==null?new BigDecimal("0"):finishOrderProductVO.getProductFinalPrice()).subtract(big));
            data.put("productFinalPrice", finishOrderProductVO.getProductFinalPrice()==null?new BigDecimal("0"):finishOrderProductVO.getProductFinalPrice());  //产品成交价
            data.put("paidMoney", finishOrderProductVO.getPaidMoney());  //产品当前回款
            data.put("residueMoney", finishOrderProductVO.getResidueMoney());  //产品当前尾款
            data.put("productCategories", finishOrderProductVO.getProductCategories());  //产品分类:0:非会员:1:会员；
        }
        return data;
    }
}